package com.coscon.controller.base;


import com.coscon.enums.SessionKey;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;

import javax.servlet.http.HttpServletRequest;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

@Slf4j
public class BaseController {



    /*        *
     *InputStream 转 byte[]
     * @author 409390047@qq.com
     * @date 2019/4/11
     * @param [inStream]
     * @return byte[]
     */
    public final byte[] input2byte(InputStream inStream)
            throws IOException {
        ByteArrayOutputStream swapStream = new ByteArrayOutputStream();
        byte[] buff = new byte[100];
        int rc = 0;
        while ((rc = inStream.read(buff, 0, 100)) > 0) {
            swapStream.write(buff, 0, rc);
        }
        byte[] in2b = swapStream.toByteArray();
        return in2b;
    }

    /**
     * @param @param  buf
     * @param @return 设定文件
     * @return InputStream    返回类型
     * @throws
     * @Title: byte2Input
     * @Description: TODO(byte数组转换inputstream)
     */
    public final InputStream byte2Input(byte[] buf) {
        return new ByteArrayInputStream(buf);
    }

    /**
     * @param @return 设定文件
     * @return String    返回类型
     * @throws
     * @Title: getUUID
     * @Description: TODO(返回一个UUID)
     */
    public final String getUuid() {
        return StringUtils.replace(UUID.randomUUID().toString(), "-", "");
    }


    public final boolean isDomainVisit(HttpServletRequest request) {
        boolean isDomainVisit = StringUtils.containsIgnoreCase(request.getHeader("Referer"), "www");
        return isDomainVisit;
    }

    /**
     * 获取当前用户
     *
     * @return 返回用户id
     */
    public String getCurrentUserId() {
        Session session = SecurityUtils.getSubject().getSession();
        if (null == session) {
            return null;
        }
        return session.getAttribute(SessionKey.UserId.getKey()).toString();
    }

    /**
     * 获取webscoket url地址
     * @param request
     * @return
     */
    public String getWebScoketUrl(HttpServletRequest request){
        StringBuffer sb = new StringBuffer("ws://"); //ws://192.168.0.134:8888/jm/socket/oneToMany
        sb.append(request.getServerName()).append(":").append(request.getServerPort());
        if(StringUtils.isNotBlank(request.getContextPath())){
            sb.append(request.getContextPath());
        }
        sb.append("/jm/socket/oneToMany");
        return sb.toString();
    }

}
